import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import '../providers/bookshelf_provider.dart';
import '../providers/comic_provider.dart'; // 保留bottomNavIndexProvider
import '../providers/auth_provider.dart'; // 添加这行
import '../screens/home/model/comic_category_item_model.dart';
import '../utils/user_manager.dart';
import '../widgets/login_dialog.dart';

class BookshelfScreen extends ConsumerStatefulWidget {
  const BookshelfScreen({super.key});

  @override
  ConsumerState<BookshelfScreen> createState() => _BookshelfScreenState();
}

class _BookshelfScreenState extends ConsumerState<BookshelfScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late ScrollController _favoritesScrollController;
  late ScrollController _historyScrollController;

  // 移除这行：bool _isLoggedIn = false; // 登录状态

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _favoritesScrollController = ScrollController();
    _historyScrollController = ScrollController();

    // 移除 _checkLogin() 调用

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        ref.read(bookshelfTabProvider.notifier).state = _tabController.index;
        ref.read(isSelectionModeProvider.notifier).state = false;
        ref.read(selectedComicsProvider.notifier).state = {};
      }
    });

    // 修改滚动监听器，使用 authProvider 的登录状态
    _favoritesScrollController.addListener(() {
      if (_favoritesScrollController.position.pixels >=
          _favoritesScrollController.position.maxScrollExtent - 200) {
        final isLoggedIn = ref.read(authProvider).isLoggedIn;
        if (isLoggedIn) {
          ref.read(favoritesProvider.notifier).loadMore();
        }
      }
    });

    _historyScrollController.addListener(() {
      if (_historyScrollController.position.pixels >=
          _historyScrollController.position.maxScrollExtent - 200) {
        final isLoggedIn = ref.read(authProvider).isLoggedIn;
        if (isLoggedIn) {
          ref.read(historyProvider.notifier).loadMore();
        }
      }
    });
  }

  // 移除整个 _checkLogin 方法
  // Future<void> _checkLogin() async { ... }

  @override
  void dispose() {
    _tabController.dispose();
    _favoritesScrollController.dispose();
    _historyScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final authState = ref.watch(authProvider);
    final isLoggedIn = authState.isLoggedIn;
    final isSelectionMode = ref.watch(isSelectionModeProvider);
    final selectedComics = ref.watch(selectedComicsProvider);

    // 监听登录状态变化，当登录成功时刷新数据
    ref.listen<AuthState>(authProvider, (previous, current) {
      if (previous?.isLoggedIn == false && current.isLoggedIn == true) {
        // 登录成功，刷新书架数据
        ref.read(favoritesProvider.notifier).refresh();
        ref.read(historyProvider.notifier).refresh();
      }
    });

    // 如果未登录
    if (!isLoggedIn) {
      return _buildLoginPrompt(context);
    }

    final favoritesState = ref.watch(favoritesProvider);
    final historyState = ref.watch(historyProvider);

    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      appBar: AppBar(
        elevation: 0,
        backgroundColor: const Color(0xFF211839),
        title: const Text(
          'Mine',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: false,
        actions: [
          GestureDetector(
            onTap: () {
              if (context.mounted) {
                final container = ProviderScope.containerOf(context);
                container.read(bottomNavIndexProvider.notifier).state = 2;
              }
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: const Color(0xFFe648aa),
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Text(
                'Premium',
                style: TextStyle(
                  fontStyle: FontStyle.italic,
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          const SizedBox(
            width: 16,
          ),
          // IconButton(
          //   onPressed: () {
          //     if (isSelectionMode) {
          //       ref.read(isSelectionModeProvider.notifier).state = false;
          //       ref.read(selectedComicsProvider.notifier).state = {};
          //     } else {
          //       ref.read(isSelectionModeProvider.notifier).state = true;
          //     }
          //   },
          //   icon: Icon(
          //     isSelectionMode ? Icons.close : Icons.delete_outline,
          //     color: Colors.white,
          //   ),
          // ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: const Color(0xFFe648aa),
          labelColor: const Color(0xFFe648aa),
          unselectedLabelColor: Colors.grey[400],
          indicator: const CustomRoundedIndicator(
            radius: 2.5,
            height: 5,
            topOffset: 36,
            color: Color(0xFFe648aa),
          ),
          dividerHeight: 0,
          unselectedLabelStyle: const TextStyle(
            fontSize: 15,
            fontWeight: FontWeight.w400,
          ),
          labelStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
          indicatorSize: TabBarIndicatorSize.label,
          indicatorWeight: 4,
          tabs: const [
            Tab(text: 'Favourites'),
            Tab(text: 'History'),
          ],
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children: [
                  // Favourites Tab
                  _buildComicsTab(
                    favoritesState,
                    _favoritesScrollController,
                    isSelectionMode,
                    selectedComics,
                  ),
                  // History Tab
                  _buildComicsTab(
                    historyState,
                    _historyScrollController,
                    isSelectionMode,
                    selectedComics,
                  ),
                ],
              ),
            ),
            if (isSelectionMode) _buildBottomActionBar(selectedComics),
          ],
        ),
      ),
    );
  }

  Widget _buildComicsTab(
    BookshelfState state,
    ScrollController scrollController,
    bool isSelectionMode,
    Set<String> selectedComics,
  ) {
    if (state.isLoading) {
      return const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
        ),
      );
    }

    if (state.hasError) {
      return RefreshIndicator(
        onRefresh: () async {
          print('[书架下拉刷新-错误状态] 开始刷新，当前Tab索引: ${_tabController.index}');
          // 等待刷新操作完成
          if (_tabController.index == 0) {
            print('[书架下拉刷新-错误状态] 刷新收藏列表');
            await ref.read(favoritesProvider.notifier).refresh();
          } else {
            print('[书架下拉刷新-错误状态] 刷新历史记录');
            await ref.read(historyProvider.notifier).refresh();
          }
          print('[书架下拉刷新-错误状态] 刷新完成');
        },
        color: const Color(0xFF8A7CA8),
        backgroundColor: const Color(0xFF211839),
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: SizedBox(
            height: MediaQuery.of(context).size.height - 200,
            child: _buildErrorState(() {
              if (_tabController.index == 0) {
                ref.read(favoritesProvider.notifier).retry();
              } else {
                ref.read(historyProvider.notifier).retry();
              }
            }),
          ),
        ),
      );
    }

    if (state.items.isEmpty) {
      return RefreshIndicator(
        onRefresh: () async {
          print('[书架下拉刷新-空状态] 开始刷新，当前Tab索引: ${_tabController.index}');
          // 等待刷新操作完成
          if (_tabController.index == 0) {
            print('[书架下拉刷新-空状态] 刷新收藏列表');
            await ref.read(favoritesProvider.notifier).refresh();
          } else {
            print('[书架下拉刷新-空状态] 刷新历史记录');
            await ref.read(historyProvider.notifier).refresh();
          }
          print('[书架下拉刷新-空状态] 刷新完成');
        },
        color: const Color(0xFF8A7CA8),
        backgroundColor: const Color(0xFF211839),
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: SizedBox(
            height: MediaQuery.of(context).size.height - 200,
            child: _buildEmptyState(),
          ),
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        print('[书架下拉刷新] 开始刷新，当前Tab索引: ${_tabController.index}');
        // 等待刷新操作完成
        if (_tabController.index == 0) {
          print('[书架下拉刷新] 刷新收藏列表');
          await ref.read(favoritesProvider.notifier).refresh();
        } else {
          print('[书架下拉刷新] 刷新历史记录');
          await ref.read(historyProvider.notifier).refresh();
        }
        print('[书架下拉刷新] 刷新完成');
      },
      color: const Color(0xFF8A7CA8),
      backgroundColor: const Color(0xFF211839),
      child: CustomScrollView(
        controller: scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        slivers: [
          SliverPadding(
            padding: const EdgeInsets.all(16),
            sliver: SliverGrid(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: 0.65,
                crossAxisSpacing: 12,
                mainAxisSpacing: 16,
              ),
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  if (index < state.items.length) {
                    final comic = state.items[index];
                    final isSelected = selectedComics.contains(comic.id);
                    return _buildComicItem(comic, isSelectionMode, isSelected);
                  } else {
                    return _buildAddComicsCard();
                  }
                },
                childCount: state.items.length + 1,
              ),
            ),
          ),
          if (state.isLoadingMore)
            const SliverToBoxAdapter(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Center(
                  child: CircularProgressIndicator(
                    valueColor:
                        AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildComicItem(
    ComicItemModel comic,
    bool isSelectionMode,
    bool isSelected,
  ) {
    return GestureDetector(
      onTap: () {
        if (isSelectionMode) {
          final currentSelected = ref.read(selectedComicsProvider);
          if (isSelected) {
            ref.read(selectedComicsProvider.notifier).state =
                currentSelected.difference({comic.id ?? ''});
          } else {
            ref.read(selectedComicsProvider.notifier).state =
                currentSelected.union({comic.id ?? ''});
          }
        } else {
          // 直接跳转到阅读页面，使用漫画ID作为chapterId
          if (comic.id != null) {
            context.pushNamed(
              'direct_reader',
              pathParameters: {
                'chapterId': comic.id ?? '',
                'comicId': comic.id ?? '',
              },
            );
          }
        }
      },
      child: Column(
        children: [
          Expanded(
            child: Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    imageUrl: comic.cover ?? '',
                    fit: BoxFit.cover,
                    width: double.infinity,
                    placeholder: (context, url) => Container(
                      color: const Color(0xFF2A1F3D),
                      child: const Icon(
                        Icons.image,
                        color: Color(0xFF8B7AA8),
                      ),
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: const Color(0xFF2A1F3D),
                      height: double.infinity,
                      child: const Icon(
                        Icons.error,
                        color: Color(0xFF8B7AA8),
                      ),
                    ),
                  ),
                ),
                if (isSelectionMode)
                  Positioned(
                    bottom: 8,
                    left: 8,
                    child: Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: isSelected
                            ? const Color(0xFFe648aa)
                            : Colors.white.withOpacity(0.3),
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: Colors.white,
                          width: 2,
                        ),
                      ),
                      child: isSelected
                          ? const Icon(
                              Icons.check,
                              color: Colors.white,
                              size: 16,
                            )
                          : null,
                    ),
                  ),
              ],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            comic.title ?? 'Unknown',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w500,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildAddComicsCard() {
    return GestureDetector(
      onTap: () {
        // 跳转到发现页面
        final container = ProviderScope.containerOf(context);
        container.read(bottomNavIndexProvider.notifier).state = 1;
      },
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xFF2A1F3D),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: Colors.white.withOpacity(0.2),
            style: BorderStyle.solid,
          ),
        ),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.add,
              color: Color(0xFF8B7AA8),
              size: 32,
            ),
            SizedBox(height: 8),
            Text(
              'Add Comics',
              style: TextStyle(
                color: Color(0xFF8B7AA8),
                fontSize: 12,
                fontWeight: FontWeight.w500,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.library_books_outlined,
            color: Colors.white.withOpacity(0.3),
            size: 64,
          ),
          const SizedBox(height: 16),
          Text(
            'No Comics Yet',
            style: TextStyle(
              color: Colors.white.withOpacity(0.7),
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Start reading to see your comics here',
            style: TextStyle(
              color: Colors.white.withOpacity(0.5),
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              final container = ProviderScope.containerOf(context);
              container.read(bottomNavIndexProvider.notifier).state = 1;
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF8A7CA8),
              padding: const EdgeInsets.symmetric(
                horizontal: 24,
                vertical: 12,
              ),
            ),
            child: const Text(
              'Discover Comics',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorState(VoidCallback onRetry) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.white.withOpacity(0.3),
            size: 64,
          ),
          const SizedBox(height: 16),
          Text(
            'Failed to Load',
            style: TextStyle(
              color: Colors.white.withOpacity(0.7),
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Please check your connection and try again',
            style: TextStyle(
              color: Colors.white.withOpacity(0.5),
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: onRetry,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF8A7CA8),
              padding: const EdgeInsets.symmetric(
                horizontal: 24,
                vertical: 12,
              ),
            ),
            child: const Text(
              'Retry',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomActionBar(Set<String> selectedComics) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFF2A1F3D),
        border: Border(
          top: BorderSide(
            color: Colors.white.withOpacity(0.1),
          ),
        ),
      ),
      child: Row(
        children: [
          Text(
            '${selectedComics.length} selected',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 16,
            ),
          ),
          const Spacer(),
          TextButton(
            onPressed: selectedComics.isEmpty
                ? null
                : () {
                    // 实现删除逻辑
                    _showDeleteConfirmDialog(selectedComics);
                  },
            child: Text(
              'Delete',
              style: TextStyle(
                color: selectedComics.isEmpty
                    ? Colors.grey
                    : const Color(0xFFe648aa),
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _showDeleteConfirmDialog(Set<String> selectedComics) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF2A1F3D),
        title: const Text(
          'Delete Comics',
          style: TextStyle(color: Colors.white),
        ),
        content: Text(
          'Are you sure you want to delete ${selectedComics.length} comic(s)?',
          style: const TextStyle(color: Colors.white70),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              'Cancel',
              style: TextStyle(color: Colors.grey),
            ),
          ),
          TextButton(
            onPressed: () {
              // 实现删除逻辑
              Navigator.of(context).pop();
              ref.read(isSelectionModeProvider.notifier).state = false;
              ref.read(selectedComicsProvider.notifier).state = {};
            },
            child: const Text(
              'Delete',
              style: TextStyle(color: Color(0xFFe648aa)),
            ),
          ),
        ],
      ),
    );
  }

  /// 未登录提示
  Widget _buildLoginPrompt(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.lock_outline,
              color: Colors.white54,
              size: 64,
            ),
            const SizedBox(height: 16),
            const Text(
              'Please log in to view your bookshelf',
              style: TextStyle(color: Colors.white70, fontSize: 16),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: () async {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (context) => const LoginDialog(),
                );
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFe648aa),
                padding:
                    const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
              ),
              child: const Text(
                'Log In',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 自定义指示器
class CustomRoundedIndicator extends Decoration {
  final double radius;
  final double height;
  final double topOffset;
  final Color color;

  const CustomRoundedIndicator({
    required this.radius,
    required this.height,
    required this.topOffset,
    required this.color,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _CustomRoundedIndicatorPainter(
      radius: radius,
      height: height,
      topOffset: topOffset,
      color: color,
    );
  }
}

class _CustomRoundedIndicatorPainter extends BoxPainter {
  final double radius;
  final double height;
  final double topOffset;
  final Color color;

  _CustomRoundedIndicatorPainter({
    required this.radius,
    required this.height,
    required this.topOffset,
    required this.color,
  });

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;

    final rect = Rect.fromLTWH(
      offset.dx,
      offset.dy + topOffset,
      configuration.size!.width,
      height,
    );

    final rrect = RRect.fromRectAndRadius(rect, Radius.circular(radius));
    canvas.drawRRect(rrect, paint);
  }
}
